package com.example.weather_app;

import static com.example.weather_app.PhotoSelect.getBackgroundResource;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.weather_app.core.BrightnessUtils;
import com.example.weather_app.core.ForecastAdapter;
import com.example.weather_app.core.ForecastDayData;
import com.example.weather_app.core.Network;
import com.example.weather_app.core.WeatherData;


import com.example.weather_app.diary.DiaryActivity;

import com.example.weather_app.music.MusicActivity;
import com.example.weather_app.position.SearchCityActivity;
import com.google.android.material.card.MaterialCardView;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "WeatherApp";
    private final ExecutorService executor = Executors.newSingleThreadExecutor();
    private String city_name = "北京";

    // 视图组件声明
    private TextView tvLocation, tvPm25, tvHumidity, tvTempValue, tvFeelsLike;
    private TextView tvTempRange, tvAirQuality, tvWind, tvHealthTips;
    private RecyclerView recyclerViewForecast;
    private LinearLayout rootLayout;
    private ProgressDialog progressDialog;

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 100;
    private List<Address> geocodeResult;
    private static final int WHAT_LOCATE = 3;

    private static final int REQUEST_SEARCH_CITY = 101;
    private ImageView ivSearchCity;
    private MaterialCardView btnMusic;
    private MaterialCardView btnDiary;
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == WHAT_LOCATE) {
                // 关闭进度对话框
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }

                if (geocodeResult != null && !geocodeResult.isEmpty()) {
                    String location = geocodeResult.get(0).getLocality();
                    if (!location.isEmpty()) {
                        city_name = location.replace("市", ""); // 移除"市"后缀
                        Log.d(TAG, "定位城市: " + city_name);
                        tvLocation.setText(city_name);
                        fetchWeatherData(new Network(MainActivity.this), city_name);//匿名内部类中的
                        Toast.makeText(MainActivity.this, "定位成功: " + city_name, Toast.LENGTH_SHORT).show();
                    } else {
                        showLocationError("城市名获取失败");
                    }
                } else {
                    showLocationError("地理编码结果为空");
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "Activity created, default city: " + city_name);

        initViews();
        checkLocationServices(); // 检查定位服务状态
        requestLocation();

        // 绑定定位按钮并设置点击事件
        TextView btnLocation = findViewById(R.id.main_area);
        btnLocation.setOnClickListener(v -> requestLocation());

        // 默认加载北京天气（定位成功后会刷新）
        fetchWeatherData(new Network(this), city_name);

        // 搜索图标点击事件
        ivSearchCity.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, SearchCityActivity.class);
            startActivityForResult(intent, REQUEST_SEARCH_CITY);
        });
        // 修改findViewById的类型为MaterialCardView
        btnMusic = findViewById(R.id.btn_music);
        btnDiary = findViewById(R.id.btn_diary);

        // 设置点击事件
        btnMusic.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, MusicActivity.class);
            startActivity(intent);
        });

        btnDiary.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, DiaryActivity.class);
            startActivity(intent);
        });

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.weather_app.diary.SCHEDULE_REMINDER");

    }

    private void initViews() {
        tvLocation = findViewById(R.id.main_area);
        tvPm25 = findViewById(R.id.main_pm2_5);
        tvHumidity = findViewById(R.id.main_humidity);
        tvTempValue = findViewById(R.id.main_temp_value);
        tvFeelsLike = findViewById(R.id.tv_feels_like);
        tvTempRange = findViewById(R.id.main_temp_range);
        tvAirQuality = findViewById(R.id.main_air_quality);
        tvWind = findViewById(R.id.main_wind);
        tvHealthTips = findViewById(R.id.main_healthTips);
        recyclerViewForecast = findViewById(R.id.recycler_forecast);
        recyclerViewForecast.setLayoutManager(new LinearLayoutManager(this));
        rootLayout = findViewById(R.id.root_layout);
        ivSearchCity = findViewById(R.id.iv_search_city);
    }
    // 检查定位服务是否开启，并且跳到设置界面，就一个检查功能
    private void checkLocationServices() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);//获取定位服务实例
        boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);//判断有没有开启gps
        boolean networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);//或判断有没有开启wifi

        if (!gpsEnabled && !networkEnabled) {
            Toast.makeText(this, "请开启定位服务", Toast.LENGTH_LONG).show();
            startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));//跳转系统设置
        }
    }

    // 处理城市搜索返回结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SEARCH_CITY && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                String selectedCity = data.getStringExtra("city_name");
                if (selectedCity != null) {
                    city_name = selectedCity;
                    tvLocation.setText(city_name);
                    fetchWeatherData(new Network(this), city_name); // 刷新天气
                }
            }
        }
    }
    // 定位核心方法
    @SuppressLint("MissingPermission")
    private void startLocation() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();//定位条件配置器，用于告诉系统 “我需要什么样的定位服务”。
        criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
        criteria.setAccuracy(Criteria.ACCURACY_COARSE); // 粗略定位（优先网络）

        // 优先使用网络定位，找定位供应商
        String provider = LocationManager.NETWORK_PROVIDER;
        if (!locationManager.isProviderEnabled(provider)) {
            provider = LocationManager.GPS_PROVIDER; // 退而求其次使用GPS
            if (!locationManager.isProviderEnabled(provider)) {
                showLocationError("定位服务未开启");
                return;
            }
        }

        Location location = locationManager.getLastKnownLocation(provider);//获取最后已知的位置
        if (location != null) {
            new Thread(() -> {
                try {
                    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
                    geocodeResult = geocoder.getFromLocation(
                            location.getLatitude(),
                            location.getLongitude(),
                            1 // 只获取一个结果
                    );
                    mHandler.sendEmptyMessage(WHAT_LOCATE); // 通知主线程更新UI
                } catch (IOException e) {
                    Log.e(TAG, "地理编码失败: " + e.getMessage());
                    showLocationError("地理编码失败");
                }
            }).start();
        } else {
            // 尝试请求更新位置（原代码未包含此逻辑）
            try {
                locationManager.requestLocationUpdates(provider, 0, 0, newlocation -> {
                    if (location != null) {
                        new Thread(() -> {
                            try {
                                Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
                                geocodeResult = geocoder.getFromLocation(
                                        location.getLatitude(),
                                        location.getLongitude(),
                                        1
                                );//geocodeResult 和 city_name 是 MainActivity 的成员变量，子线程和主线程共享访问。
                                mHandler.sendEmptyMessage(WHAT_LOCATE);//提醒
                            } catch (IOException e) {
                                Log.e(TAG, "地理编码失败: " + e.getMessage());
                                showLocationError("地理编码失败");
                            }
                        }).start();
                    } else {
                        showLocationError("获取位置失败");
                    }
                });
            } catch (SecurityException e) {
                Log.e(TAG, "定位权限不足: " + e.getMessage());
                showLocationError("定位权限不足");
            }
        }
    }

    // 请求定位权限

    private void requestLocation() {
        // 检查定位服务
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!gpsEnabled && !networkEnabled) {
            Toast.makeText(this, "请开启定位服务", Toast.LENGTH_LONG).show();
            startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            return;
        }

        // 检查定位权限（合并后的逻辑）
        boolean hasFinePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        boolean hasCoarsePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        if (!hasFinePermission && !hasCoarsePermission) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
            return;
        }

        // 权限和服务都就绪，显示进度对话框并启动定位
        progressDialog = ProgressDialog.show(this, "定位中", "正在获取当前位置...", true, false);
        startLocation();
    }

    // 权限请求结果处理
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            // 检查是否至少有一个定位权限被授予
            boolean fineGranted = false;
            boolean coarseGranted = false;

            // 遍历权限结果数组（可能包含两个权限）
            for (int i = 0; i < permissions.length; i++) {
                if (permissions[i].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
                    fineGranted = grantResults[i] == PackageManager.PERMISSION_GRANTED;
                } else if (permissions[i].equals(Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    coarseGranted = grantResults[i] == PackageManager.PERMISSION_GRANTED;
                }
            }

            if (fineGranted || coarseGranted) {
                // 至少有一个权限被授予，执行定位
                startLocation();
            } else {
                // 两个权限都被拒绝，处理降级逻辑
                Toast.makeText(this, "定位权限被拒绝，使用默认位置: " + city_name, Toast.LENGTH_SHORT).show();
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }

                // 额外处理：若用户勾选"不再询问"，引导至设置页
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) &&
                        !ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    showSettingsGuide();
                }
            }
        }
    }

    // 引导用户至设置页的辅助方法
    private void showSettingsGuide() {
        Toast.makeText(this, "请在设置中手动开启定位权限", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivity(intent);
    }

    // 统一错误提示
    private void showLocationError(String message) {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

        runOnUiThread(() -> {
            Toast.makeText(MainActivity.this, "定位失败: " + message, Toast.LENGTH_SHORT).show();
            Log.w(TAG, "定位失败: " + message);
        });
    }

    // 天气数据获取（保持原逻辑）
    private void fetchWeatherData(Network network, String cityName) {
        Log.d(TAG, "Fetching weather for: " + cityName);
        executor.execute(() -> {
            try {
                WeatherData data = network.getWeatherData(cityName);
                runOnUiThread(() -> updateUI(data));
            } catch (Exception e) {
                Log.e(TAG, "获取天气数据失败: " + e.getMessage(), e);
                runOnUiThread(() -> Toast.makeText(
                        MainActivity.this,
                        "错误: " + e.getMessage(),
                        Toast.LENGTH_LONG
                ).show());
            }
        });
    }

    // UI更新（保持原逻辑）
    private void updateUI(WeatherData data) {
        Log.d(TAG, "Updating UI for city: " + city_name);

        tvLocation.setText(city_name);
        tvPm25.setText("PM2.5: " + data.getPm25());

        if (data.getHumidity() != null) tvHumidity.setText("湿度: " + data.getHumidity());
        if (data.getCurrentTemp() != null) {
            try {
                double currentTemp = Double.parseDouble(data.getCurrentTemp());
                tvTempValue.setText(String.valueOf((int) Math.round(currentTemp)));
                tvFeelsLike.setText("体感 " + data.getCurrentTemp() + "°C");
            } catch (NumberFormatException e) {
                Log.e(TAG, "Invalid temperature format: " + data.getCurrentTemp());
            }
        }

        if (data.getAirQuality() != null) tvAirQuality.setText(data.getAirQuality());

        if (!data.getForecastList().isEmpty()) {
            ForecastDayData today = data.getForecastList().get(0);
            if (today.getLowTemp() != null && today.getHighTemp() != null) {
                tvTempRange.setText(today.getLowTemp() + " ~ " + today.getHighTemp());
            }
            if (today.getWindDir() != null && today.getWindLevel() != null) {
                tvWind.setText("风向：" + today.getWindDir() + " 风速：" + today.getWindLevel());
            }
            if (data.getHealthTip() != null) tvHealthTips.setText(data.getHealthTip()+" "+today.getNotice());

            if (today.getWeather() != null) {
                int bgResId = getBackgroundResource(today.getWeather());
                rootLayout.setBackgroundResource(bgResId);
                updateBackgroundBrightness(today);
            }
        }

        List<ForecastDayData> forecastList = data.getForecastList();
        if (forecastList != null && !forecastList.isEmpty()) {
            ForecastAdapter adapter = new ForecastAdapter(forecastList);
            recyclerViewForecast.setAdapter(adapter);
        }
    }

    // 背景亮度调整（保持原逻辑）
    private void updateBackgroundBrightness(ForecastDayData data) {
        if (data.getSun_rise() != null && data.getSun_set() != null) {
            boolean isNight = BrightnessUtils.isNightTime(
                    data.getSun_rise(),
                    data.getSun_set()
            );
            BrightnessUtils.adjustBackgroundBrightness(rootLayout, isNight);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        executor.shutdown();
        mHandler.removeCallbacksAndMessages(null);
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        Log.d(TAG, "Activity destroyed");
    }
}